import { useState } from 'react';

import { ColumnDef } from '@tanstack/react-table';
import { DialogDescription } from '@radix-ui/react-dialog';
import { useClientContext, useService, WorkflowJSON } from '@flowgram.ai/free-layout-editor';

import { cn } from '@/lib/utils';
import { useFlowContext } from '@/context/flow-context';

import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import { DataTable } from '../ui/data-table';
import { Button } from '../ui/button';
import { CustomService } from '../../services/custom-service';

interface FlowItem {
  id: string;
  name: string;
}

export function Load() {
  const customService = useService(CustomService);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selectedFlow, setSelectedFlow] = useState<FlowItem | null>(null);
  const [flows, setFlows] = useState<FlowItem[]>([]);
  const { setFlow } = useFlowContext();
  const clientContext = useClientContext();

  const columns: ColumnDef<FlowItem>[] = [
    {
      accessorKey: 'id',
      header: 'ID',
    },
    {
      accessorKey: 'name',
      header: '名称',
    },
  ];

  async function onDelete(row: FlowItem) {
    console.log('onDelete', row);
    try {
      await customService.deleteFlow(row.id);
      setFlows(flows.filter((item) => item.id !== row.id));
    } catch (e) {
      console.log('deleteFlow error', e);
    }
  }

  const flowTable = (
    <div className="rounded-md border">
      <DataTable
        columns={columns}
        data={flows}
        onDelete={onDelete}
        onSelectedRowsChange={setSelectedFlow}
      />
    </div>
  );

  async function loadFlowList() {
    const controller = new AbortController(); // Create abort controller
    setLoading(true);
    customService
      .getFlowList()
      .then((res) => {
        console.log('getFlowList', res);
        const items = res.map((item) => ({
          id: item.ID,
          name: item.Name,
        }));
        setFlows(items);
      })
      .finally(() => {
        setLoading(false);
      });

    return () => {
      controller.abort();
    };
  }

  async function onLoad() {
    if (selectedFlow) {
      console.log('onLoad', selectedFlow);
      customService
        .getFlow(JSON.stringify({ id: selectedFlow.id }))
        .then((res) => {
          setFlow({
            id: res.ID,
            name: res.Name,
          });
          setOpen(false);
          if (!res.Script) {
            throw new Error('API 返回缺少 Script 字段');
          }
          const obj = JSON.parse(res.Script);
          const doc = obj.data as WorkflowJSON;
          console.log('res.Script', doc);
          clientContext.document.fromJSON(doc);
        })
        .catch((e) => {
          console.log('getFlow', e);
        });
    }
  }
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button className={cn('h-8 w-20 rounded-md md:text-xs border')} onClick={loadFlowList}>
          加载
        </button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>加载工作流</DialogTitle>
          <DialogDescription>加载服务端工作流</DialogDescription>
        </DialogHeader>

        {loading ? <div>Loading models...</div> : flowTable}

        <DialogFooter>
          <Button onClick={onLoad}>打开</Button>
          <DialogClose asChild>
            <Button type="button" variant="secondary">
              关闭
            </Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
